import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Link} from 'dva/router';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Icon,
    Button,
    Dropdown,
    Menu,
    InputNumber,
    DatePicker,
    Modal,
    message,
    Badge,
    Divider,
} from 'antd';
const {RangePicker} = DatePicker;
import StandardTable from 'components/OrderTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {status, statusMap} from './orderStatus';
import styles from './OrderList.less';
import {stringify} from 'qs';
import {DATA_HOST,} from '../../utils/setting';
import G from '../../utils/g';

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
// const status = ['退款成功', '退款退货成功', '退款申请中', '同意退款等待退货', '退款/退货申请中'];
const columns = [
    {
        title: '订单ID',
        dataIndex: 'orderId',
        key: 'orderId',
        render(text, record){
            let result = text.toString();
            return <Link to={`order-detail?id=${record.orderId}`}>{result.substr(result.length - 4)}</Link>; //取后四位显示
        }
    },
    {
        title: '商品',
        width: 250,
        render(text, record) {
            let result = '';
            const sku = JSON.parse(record.sku);
            for (let key in sku) {
                result = record.sku[key];
            }
            return (<Link to="/">
                <img className={styles.goodsPic} src={`${record.img}?imageView2/2/w/50`} width={50} />
                <p className={styles.goodsName}>
                    {record.name}<br/>
                    <span className={styles.goodsColor}>{result}</span>
                </p>
            </Link>);
        },
    },
    {
      title: '用户',
      render: (_, record)=>`${record.addressee}/${record.phone}`
    },
    {
        title: '退款原因',
        dataIndex: 'reason',
        key: 'reason'
    },
    {
        title: '退款方式',
        dataIndex: 'expected_result',
        key: 'expected_result',
    },
    {
        title: '订单金额',
        align: 'right',
        render: (val, record)=> {
            return (<div>
                {record.price}
            </div>);
        }
    },
    {
        title: '退款金额',
        align: 'right',
        render: (val, record)=> {
            return (<div>
                { record.refund_price }
            </div>);
        }
    },
    {
        title: '申请时间',
        dataIndex: 'createTime',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
        title: '状态',
        dataIndex: 'status',
        filters: [
            {
                text: status[0],
                value: 0,
            },
            {
                text: status[1],
                value: 1,
            },
            {
                text: status[2],
                value: 2,
            },
            {
                text: status[3],
                value: 3,
            },
        ],
        render(val) {
            return <Badge status={statusMap[val]} text={status[val]}/>;
        },
    },
    {
        title: '操作',
        render: (a, b) => (
            <Fragment>
                <Link to={`refund-detail?id=${b.id}`}>详情</Link>
            </Fragment>
        ),
    },
];

const CreateForm = Form.create()(props => {
    const {modalVisible, form, handleAdd, handleModalVisible} = props;
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            form.resetFields();
            handleAdd(fieldsValue);
        });
    };
    return (
        <Modal
            title="新建规则"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={() => handleModalVisible()}
        >
            <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="描述">
                {form.getFieldDecorator('desc', {
                    rules: [{required: true, message: 'Please input some description...'}],
                })(<Input placeholder="请输入"/>)}
            </FormItem>
        </Modal>
    );
});

@connect(({refundList, loading}) => ({
    refundList,
    loading: loading.models.rule,
}))
@Form.create()
export default class TableList extends PureComponent {
    state = {
        modalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'refundList/fetch',
            payload: {}
        });
    }

    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            startIndex: ( pagination.current - 1 ) * pagination.pageSize,  //此处峻吉分页需要是第一项的序号，如第二页传10，而不是具体的分页码1，2，3
            pageSize: pagination.pageSize,
            ...formValues,
            ...filters,

        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'refundList/fetch',
            payload: params,
        });
    };

    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        this.setState({
            formValues: {},
        });
        dispatch({
            type: 'refundList/fetch',
            payload: {}
        });
    };

    toggleForm = () => {
        this.setState({
            expandForm: !this.state.expandForm,
        });
    };

    handleMenuClick = e => {
        const {dispatch} = this.props;
        const {selectedRows} = this.state;

        if (!selectedRows) return;

        switch (e.key) {
            case 'remove':
                dispatch({
                    type: 'refundList/remove',
                    payload: {
                        no: selectedRows.map(row => row.no).join(','),
                    },
                    callback: () => {
                        this.setState({
                            selectedRows: [],
                        });
                    },
                });
                break;
            default:
                break;
        }
    };

    handleSelectRows = rows => {
        this.setState({
            selectedRows: rows,
        });
    };

    handleSearch = e => {
        e.preventDefault();

        const {dispatch, form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;

            const values = {
                ...fieldsValue,
            };
            if (Array.isArray(fieldsValue.time)) {
                values.startTime = fieldsValue.time[0].format('YYYY-MM-DD');
                values.endTime = fieldsValue.time[1].format('YYYY-MM-DD');
            }
            delete values.time;

            this.setState({
                formValues: values,
            });

            dispatch({
                type: 'refundList/fetch',
                payload: values,
            });
        });
    };
    handleExportOrder = ()=> { //导出查询订单
        const {dispatch, form} = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;

            const values = {
                ...fieldsValue,
                token: window.localStorage.token
            };
            if (Array.isArray(fieldsValue.time)) {
                values.startTime = fieldsValue.time[0].format('YYYY-MM-DD');
                values.endTime = fieldsValue.time[1].format('YYYY-MM-DD');
            }
            delete values.time;
            const sign = G.md5Encrypt(values);
            const href = DATA_HOST + '/dashboard/excel/refund/?' + stringify(values) + '&sign=' + sign
            console.log('href', href);
            window.open(href);
        })
    };

    handleModalVisible = flag => {
        this.setState({
            modalVisible: !!flag,
        });
    };

    handleAdd = fields => {
        this.props.dispatch({
            type: 'refundList/add',
            payload: {
                description: fields.desc,
            },
        });

        message.success('添加成功');
        this.setState({
            modalVisible: false,
        });
    };

    renderForm() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="退款编号">
                            {getFieldDecorator('id')(<Input placeholder="请输入"/>)}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="订单号">
                            {getFieldDecorator('orderId')(<Input placeholder="请输入"/>)}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="退款方式">
                            {getFieldDecorator('expected_result')(
                                <Select placeholder="请选择" style={{width: '100%'}}>
                                    <Option value="退货退款">退货退款</Option>
                                    <Option value="仅退款">仅退款</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>

                </Row>
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="退款状态">
                            {getFieldDecorator('status')(
                                <Select placeholder="请选择" style={{width: '100%'}}>
                                    <Option value="200">申请退款</Option>
                                    <Option value="201">申请退货</Option>
                                    <Option value="202">卖家确认退货</Option>
                                    <Option value="203">卖家确认退款</Option>
                                    <Option value="204">买家退货</Option>
                                    <Option value="205">退款成功</Option>
                                    <Option value="206">退款关闭</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="下单时间">
                            {getFieldDecorator('time')(
                                <RangePicker style={{width: '100%'}} placeholder={['开始日期', '结束日期']}/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleExportOrder}>
                报表导出
              </Button>
            </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    render() {
        const {refundList: {data}, loading} = this.props;
        const {selectedRows, modalVisible} = this.state;

        const parentMethods = {
            handleAdd: this.handleAdd,
            handleModalVisible: this.handleModalVisible,
        };

        return (
            <div>
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderForm()}</div>
                        <div className={styles.tableListOperator}>
                        </div>
                        <StandardTable
                            loading={loading}
                            data={data}
                            columns={columns}
                            onChange={this.handleStandardTableChange}
                            rowKey={'id'}
                            expandedRowRender={null}
                        />
                    </div>
                </Card>
                <CreateForm {...parentMethods} modalVisible={modalVisible}/>
            </div>
        );
    }
}
